﻿using System;
using System.Windows.Input;
using Ninject.Core.Parameters;
using TestBat.IModels.Domain;
using TestBat.IModels.Models;
using TestBat.IViewModels.Workspaces.Trainees;
using TestBat.ServiceLocator;
using TestBat.ViewModels.Attributes;
using TestBat.ViewModels.Base;
using TestBat.ViewModels.Base.Commands;

namespace TestBat.ViewModels.Workspaces.Trainees
{
    public class AddTraineeViewModel : ViewModel, IAddTraineeViewModel
    {
        public AddTraineeViewModel(ITraineeModel traineeModel)
        {
            this.traineeModel = traineeModel;

            Trainee = DefaultServiceLocator.Get<ITrainee>(With.Parameters.Variable("manual", true)); // TODO: use factory
            //Trainee.Group = traineeGroup;
        }

        public ICommand AddCommand
        {
            get
            {
                return new RelayCommand(e => Add());
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new RelayCommand(e => Cancel());
            }
        }

        public event OnCancel OnCancel;
        public event OnAddTrainee OnAdd;

        public ITrainee Trainee { get; private set; }

        [BusinessErrorDialog]
        [ValidationErrorDialog]
        private void Add()
        {
            // HACK: unfortunately, we need to set back the identifier to make sure NHibernate treats it as a new entity
            // the reason, why the entity even gets an ID even if it's not persisted is the following:
            // when you try to persist a new entity, NHibernate first generates a new ID for it. But if the transaction fails somehow, the entity is still transient but the ID stays.
            // When you try to commit this entity again, NHibernate throws a StaleStateException, expecting to find the entity in the DB already (as it has an identifier)
            Trainee.ID = Guid.Empty;
            // END HACK
            traineeModel.Save(Trainee);
            if (OnAdd != null)
                OnAdd(Trainee);
        }

        private void Cancel()
        {
            if (OnCancel != null)
                OnCancel();
        }

        private readonly ITraineeModel traineeModel;
    }
}
